package cn.kais.drawer.unit;

import cn.kais.drawer.menu.MenuScoreIcon;
import org.apache.batik.transcoder.TranscoderException;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.image.PNGTranscoder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.imageio.ImageIO;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.awt.image.BufferedImage;
import java.io.*;

/**
 * 评分
 */
public class UnitScore {
    private static final Log log = LogFactory.getLog(UnitScore.class);

//    public void test(BeanScore bean) {
//        BufferedImage ima = new BufferedImage(500, 300, BufferedImage.TYPE_INT_ARGB);
//        Graphics2D sd = ima.createGraphics();
//        sd.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
//
//        // 原比例图片
//        BufferedImage score = iBasicBuffer(bean);
//        System.out.println("原图宽度：" + score.getWidth());
//        System.out.println("原图高度：" + score.getHeight());
//        sd.drawImage(score, 20, 90, null); // 原图  最好的方法是在绘制 每个五角星的时候 进行缩放
////        sd.drawImage(score, 20, 90, 399, 54, null); //缩放图
//
//        sd.dispose();
//        UnitTools.doTestWrite(ima, "TestScore");
//    }

    /**
     * 绘制一张基础图
     */
//    public static BufferedImage iBasicBuffer(BeanScore bean) {
//        Size size = SizeUtil.doCountScoreSize(bean.count, bean.space);
//        BufferedImage ima = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_ARGB);
//        Graphics2D sd = ima.createGraphics();
//        sd.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
//        BufferedImage im_a = iScoreBuffer(bean.icon, "a", bean.color); // 全图 流
//        BufferedImage im_b = iScoreBuffer(bean.icon, "b", bean.color); // 半图 流
//        BufferedImage im_c = iScoreBuffer(bean.icon, "c", bean.color); // 空图 流
//        boolean ban = false; // 是否绘制过 半图 / 0.5分图
//        for (int i = 1; i <= bean.count; i++) {
//            if (i < bean.score || i == bean.score) {
//                int x = AxisUtil.doCountScoreItemX(i, bean.space);
//                sd.drawImage(im_a, x, 0, null);
//            } else if (i > bean.score && !ban) {
//                ban = true;
//                int x = AxisUtil.doCountScoreItemX(i, bean.space);
//                sd.drawImage(im_b, x, 0, null);
//            } else {
//                int x = AxisUtil.doCountScoreItemX(i, bean.space);
//                sd.drawImage(im_c, x, 0, null);
//            }
//        }
//
//        sd.setColor(Color.BLACK);
//        BasicStroke stroke = new BasicStroke(2);
//        sd.setStroke(stroke);
//        sd.drawRect(0, 0, size.width, size.height); // 圆形  椭圆形
//        sd.dispose();
//
//        return ima;
//    }

    /**
     * 根据种类 颜色 获取 单个图片流
     *
     * @param icon  图片类型
//     * @param state 图片状态
     * @param color 图片颜色
     */
    public static BufferedImage iScoreBuffer(MenuScoreIcon icon, String color) {
        Document doc;
        try {
            doc = onGetDocument(icon);
            // 颜色值 不是黑色时 替换颜色
            if (!color.equals("000")) {
                onSetSubColor(doc, color);
            }
        } catch (IOException | SAXException | ParserConfigurationException e) {
            System.out.println("模板图片获取失败");
            return null;
        }

        String content;
        try {
            content = onGetDocumentContent(doc);
        } catch (TransformerException e) {
            System.out.println("模板内容获取失败");
            return null;
        }
        try {
            return onGetContent2Picture(content);
        } catch (TranscoderException | IOException e) {
            System.out.println("模板内容转换图片失败");
            return null;
        }
    }

    /**
     * 获取模板
     * <p>
     * //     * @param type  类型 如：星星，辣椒
     * //     * @param state 状态 如：全图，半图，空图
     */
    private static Document onGetDocument(MenuScoreIcon icon) throws IOException, SAXException, ParserConfigurationException {
//        String mPath = "src/main/resources/score/" + type + "_" + state + ".svg";
//
//        String resourcePath = UnitScore.class.getClassLoader().getResource("score/" + type + "_" + state + ".svg").getPath();
//        System.out.println(resourcePath);
//        log.info("=========：" + resourcePath);
////        String url = ResourceLoader.class.getClassLoader().getResource("score/" + type + "_" + state + ".svg").getPath();
////        System.out.println(url);
        DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = fact.newDocumentBuilder();
//        return builder.parse(resourcePath);
        String value = icon.value;
        InputStream stream = new ByteArrayInputStream(value.getBytes());
        return builder.parse(stream);
    }

    /**
     * 设置替换颜色
     *
     * @param doc   svg 图片内容
     * @param color 替换颜色
     */
    private static void onSetSubColor(Document doc, String color) {
        NodeList list = doc.getElementsByTagName("path");
        for (int i = 0; i < list.getLength(); i++) {
            Node node = list.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                Element e = (Element) node;
                e.setAttribute("fill", color);
            }
        }
    }

    /**
     * 获取 模板内容 字符串
     *
     * @param doc svg 图片内容
     */
    private static String onGetDocumentContent(Document doc) throws TransformerException {
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StringWriter writer = new StringWriter();
        transformer.transform(source, new StreamResult(writer));
        return writer.getBuffer().toString();
    }

    /**
     * 模板内容 转换 png 图片
     *
     * @param content svg 图片字符串 转 png 图片
     */
    private static BufferedImage onGetContent2Picture(String content) throws TranscoderException, IOException {
        StringReader reader = new StringReader(content);
        TranscoderInput ti = new TranscoderInput(reader);

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        TranscoderOutput to = new TranscoderOutput(bos);

        PNGTranscoder transcoder = new PNGTranscoder();
        transcoder.transcode(ti, to);
        byte[] bts = bos.toByteArray();
        bos.close();
        return ImageIO.read(new ByteArrayInputStream(bts));
    }

}
